import app from '@/main'
import axios from 'axios'
import { UserModule } from '@/store/modules/user'
import { RequestQueryBuilder, CreateQueryParams } from '@nestjsx/crud-request'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// Request interceptors
service.interceptors.request.use(
  (config) => {
    if (UserModule.token) {
      config.headers.Authorization = 'Bearer ' + UserModule.token
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// Response interceptors
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.error) {
      if (res.config.params._quiet) {
        app.$Message.error({
          content: res.error || 'Error',
          duration: 5
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return response
    }
  },
  (error) => {
    if (error.config.params?._quiet !== true && error.response.status !== 401) {
      app.$Message.error({
        content: error.response.data.message || error.message || 'Unknow response error',
        duration: 5
      })
    } else {
      console.log(error.response.data.message)
    }
    return Promise.reject(error)
  }
)

const crudParamsSerializer = (params: CreateQueryParams) => RequestQueryBuilder.create(params).query()

export { service, crudParamsSerializer }
